package com.chebaohui.iqs.sdk.util;

import java.security.Key;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import sun.misc.BASE64Decoder;

/**
 * 参数加密以及签名方式
 * 
 * @author xielonghai
 *
 */
public class RsaMd5 {
	/** md5加密指定加密方式 */
	private static char hexDigits[] = { '0', '1', '2', 'A', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'E',
			'f' };
	private static String KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHLSLttyRNUvOqo0fG3i0tGBy/A+nPO9J2A1DstaNyGPftDeaVCxrbEZVH9OUmRgLsFYRrUpRYfVzzX0ZJtBNySLnDwajG9raDmUB/V+qKzruZIAp6/WI53h+Fb+LrHAAf1Awmt4rm6MuwULozCyq9gvudTWofnSYM/kHwDzP8GwIDAQAB";

	/** 签名--MD5加密方法 */
	public static String Md5(String s) {
		byte[] btInput = s.getBytes();
		return MD5(btInput, 32);
	}

	/** 参数--RSA加密 */
	public static String getEncryption(String value) throws Exception {
		byte[] by = value.getBytes();
		byte[] res = encryptByPublicKey(by, KEY);
		String result = "";
		for (byte ii : res)
			result = result + String.valueOf(ii) + "#";
		return result;
	}

	private static byte[] encryptByPublicKey(byte[] data, String key) throws Exception {
		byte[] keyBytes = decryptBASE64(key);
		X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

		// 对数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);

		return cipher.doFinal(data);
	}

	private static byte[] decryptBASE64(String key) throws Exception {
		return (new BASE64Decoder()).decodeBuffer(key);
	}

	private static String MD5(byte[] btInput, int length) {
		try {
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (byte byte0 : md) {
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			String result = new String(str);
			return length == 16 ? result.substring(8, 24) : result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

//	public static void main(String[] args) throws Exception {
//		String txnAmt = "888";
//		String orderNumber = "orderNumber";
//		String sign = "txnAmt=" + txnAmt + "&orderId=" + orderNumber;
//		System.out.println(RsaMd5.getEncryption(txnAmt));
//		System.out.println(RsaMd5.getEncryption(orderNumber));
//		System.out.println(RsaMd5.Md5(sign));
//		System.out.println(RsaFuc.getDecryption(RsaMd5.getEncryption(txnAmt)));
//		System.out.println(RsaFuc.getDecryption(RsaMd5.getEncryption(orderNumber)));
//		System.out.println(RsaFuc.getDecryption(RsaMd5.getEncryption(sign)));
//	}
}
